package com.linkelee.manage.config;


import com.linkelee.manage.base.redis.JedisPoolConfigHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis自动注入类
 *
 * @author lsl
 * @since 2019-03-25
 */

@Configuration
public class RedisConfiguration {

    private StringRedisSerializer stringRedisSerializer
            = new StringRedisSerializer();

    private GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer
            = new GenericJackson2JsonRedisSerializer();

    @Autowired
    private JedisPoolConfigHelper jedisPoolConfigHelper;

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() throws Exception {
        return jedisPoolConfigHelper.getJedisConnectionFactory();
    }

    /**
     * 注入redis string连接
     *
     * @return
     * @throws Exception
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate() throws Exception {
        StringRedisTemplate stringRedisTemplate
                = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(jedisConnectionFactory());
        stringRedisTemplate.setKeySerializer(stringRedisSerializer);
        stringRedisTemplate.setHashValueSerializer(stringRedisSerializer);
        stringRedisTemplate.setHashKeySerializer(stringRedisSerializer);
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }

    /**
     * 注入redis object连接
     *
     * @return
     * @throws Exception
     */
    @Bean
    public RedisTemplate redisTemplate() throws Exception {
        RedisTemplate redisTemplate
                = new RedisTemplate();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}
